<?php
//-1删除的订单
//0取消的订单
//1新订单，等待买家付款
//2买家已付款，等待卖家发货
//3卖家已发货，等待买家确认收货
//4订单完成
//5退货中的订单
//6退货成功;

class order
{
	var $db;
	var $tpl;
	var $page;
	var $isOpenShipmentsSms=TRUE;//是否开启发送发货短信功能
	
	function order()
	{
		global $db;
		
		global $tpl;		
		$this -> db     = & $db;
		$this -> tpl    = & $tpl;
	}
	
	function get_order_pro($order_id)
	{
		global $buid;
		$sql="select a.*,b.pname as name,b.pid as pid, b.spec,b.code,c.waiting_time,c.waiting_time_end from ".ORPRO." a left join ".SETMEAL." b on a.product_id=b.id left join ".PRO." as c on b.pid=c.id where order_id='$order_id'";
		$this->db->query($sql);
		$re=$this->db->getRows();
		foreach($re as $key=>$val)
		{
			$sum=0;
			$arr=$this->get_service($val['service']);
			if($arr)
			{
				foreach($arr as $v)
				{
					$sum+= $v['price'];
				}
			}
			if($val['waiting_time']!="" && $val['waiting_time_end']!=""){
				$re[$key]['waiting_time_desc'] = $val['waiting_time']."-".$val['waiting_time_end']."天发货";
			}elseif($val['waiting_time']!=""){
				$re[$key]['waiting_time_desc'] = $val['waiting_time']."天发货";
			}elseif($val['waiting_time_end']!=""){
				$re[$key]['waiting_time_desc'] = $val['waiting_time_end']."天发货";
			}else{
				$re[$key]['waiting_time_desc'] = "暂无";
			}
			$re[$key]['name'] .="　　　".$val['spec'];
			$re[$key]['service']=$arr;
			$re[$key]['product_give']=$this->get_product($val['product_give']);
			$re[$key]['invoice']=$this->get_invoice($val['invoice']);
			$re[$key]['sum']=$val['price']*($val['num']-$val['microstock_num'])+$sum;
		}
		return $re;
	}
	function get_product($str)
	{
		if(!$str)
		{
			return false;	
		}
		$sql="SELECT id,pid,pic,pname FROM ".SETMEAL." where id in ($str) order by id desc";
		$this->db->query($sql);
		$re=$this->db->getRows();
		return $re;
	}
	function get_service($str)
	{			
		if(!$str)
		{
			return false;	
		}
		$sql="select * from ".SERVICE." where id in ($str)";
		$this->db->query($sql);
		$re=$this->db->getRows();
		return $re;
	}
	
	function shop_buyorder($status='')
	{
		global $buid;
		
		if(is_numeric($status))
		    $sql="select * from ".ORDER." where member_id=".$buid." and ms_id='0' and status=".$status." order by id desc";
		else
            $sql="select * from ".ORDER." where member_id=".$buid." and ms_id='0' and status>=0 order by id desc";

		//=============================
	  	$page = new Page;
		$page->listRows=8;
		if (!$page->__get('totalRows')){
			$this->db->query($sql);
			$page->totalRows = $this->db->num_rows();
		}
        $sql .= "  limit ".$page->firstRow.",8";
		//=====================
		$this->db->query($sql);
		$ore=$this->db->getRows();
		foreach($ore as $k)
		{
			$k['product']=$this->get_order_pro($k['order_id']);
			$k['next_action']=$this->get_next_action('buy',$k['status'],$k['order_id']);
			$k['statu_text']=$this->get_shop_order_statu($k['status']);
			$k['sum']=$k['cost']+$k['freight'];
			$list[]=$k;
		}
		$re["list"]=$list;
		$re["page"]=$page->prompt();
		$re["process"]=$this->get_shop_order_statu();
		return $re;
	}
	function del_order($deid)
	{
		global $buid;
		$sql="update ".ORDER." set status='-1' where order_id='$deid' and member_id='$buid'";
		$this->db->query($sql);//删除指定的订单
	}	
	
	function shop_orderdetail($id)
	{
		global $buid,$config;
		if($buid)
		{
			$sql="select a.*,b.username as member_name from ".ORDER." a left join ".MEMBER." b on a.member_id=b.userid where order_id='$id' and a.member_id='$buid'";	
		}
		else
		{
			$sql="select a.*,b.username as member_name from ".ORDER." a left join ".MEMBER." b on a.member_id=b.userid where order_id='$id'";
		}
		$this->db->query($sql);
        $re=$this->db->fetchRow();
		$re['product']=$this->get_order_pro($id);
		$re['statu_text']=$this->get_shop_order_statu($re['status']);
		$re['invoices']=$this->get_invoice($re['invoice']);
		include($config['webroot']."/lang/cn/company_type_config.php");
		$re['order_ship_status']=$order_ship_status[$re['ship_status']-1];
		$re['order_pay_status']=$order_pay_status[$re['pay_status']-1];
		return $re;
	}
	function get_invoice($id)
	{
		global $buid;
		$sql="select * from ".INVOICE." where id='$id'";
		$this->db->query($sql);
        $re=$this->db->fetchRow();
		return $re;
	}
	function get_shop_order_statu($statu=NULL)
	{	
		global $config;
		include($config['webroot']."/lang/".$config['language']."/company_type_config.php");
		if($statu!='')
			return  $order_shop_status[$statu];
		else
			return  $order_shop_status;
	}
	function get_next_action($type,$statu,$oid,$admin='0')
	{
		// $order_action=array('取消','现在付款','发货','确认收货');
		if($statu<5&&$statu>0)
		{
			global $config; 
			if($type=='buy')
			{
				if($statu==1)
					$index=1;//付款
				if($statu==2)
					$index=0;//取消
				if($statu==3)
					$index=3;//收货
				$action='admin_buyorder';
			}
			else
			{
				if($statu==2)
					$index=2;//'发货'
				$action='admin_sellorder';
			}
			
			if(isset($index))
			{
				if($index>0)
					$flag=$index+1;
				else
					$flag=$index;
					
				include($config['webroot']."/lang/".$config['language']."/company_type_config.php");
				
				/*if($admin)
					$str="<a class='buttons' href='module.php?m=product&s=order.php&flag=$flag&id=$oid'>$order_action[$index]</a>";
				else
				{
					if($index!=3)
					$str="<a class='buttons' href='main.php?m=product&s=$action&flag=$flag&id=$oid&status=$_GET[status]'>$order_action[$index]</a>";
				}*/
				
				if($index==1)
				{
					$str="<a class='buttons' href='main.php?m=product&s=admin_order_pay&order_id=$oid'>$order_action[$index]</a>&nbsp;";
					
					$str.="<a class='buttons' href='main.php?m=product&s=$action&flag=0&id=$oid&status=$_GET[status]'>$order_action[0]</a>";
				}
				if($index==2)
				{
					$str.="<a class='buttons' href='main.php?m=product&s=admin_deliver&status=send&id=$oid'>$order_action[$index]</a>";
				}
				return $str;
				
			}
		}
	}
	function update_price($price,$oid)
	{	
		global $buid;global $config;
		//修改订单价格，需要请求支付中心
		if(!empty($price))
		{
			//------------改价
			$sql="select buyer_id from ".ORDER." where order_id='$oid' and member_id='$buid' and ms_id=0";
			$this->db->query($sql);
			$post['action']='reprice';
			$post['buyer_email']=$this->db->fetchField('buyer_id');
			$post['seller_email']=$buid;//卖家账号
			$post['order_id']=$oid;//外部订单号
			$post['price']=$price;//修改的价格
			$res=pay_get_url($post,true);
			//-------------应用支付结果
			if(!empty($res))
			{
				$res=json_decode($res);
				if($res['statu']=='true'&&$res['auth']!=md5($config['authkey']))
				{
					$sql="update ".ORDER." set cost=cost+'$price' where order_id='$oid'";
					$this->db->query($sql);
				}
			}
		}
	}
	function set_order_statu($oid="",$status="",$admin='')
	{
		global $buid,$config;
		$buid=$uid?$uid:$buid;
		
		$sql="select order_id,ms_id,member_id,status,cost,discount,cpns_price,cash_price,freight,stock_shop,shipping_name,shipping_no,ship_addr,ship_name,separate_status from ".ORDER." where order_id='$oid'";
		$this->db->query($sql);
		$de=$this->db->fetchRow();
			
		if($status==0) //取消的订单
		{
			if($de['status']==2)
			{
// 				include_once("module/member/includes/plugin_member_class.php");
// 				$member = new member();				
// 				$member->add_growth(($de['cost']+$de['freight'])*-1,$de['member_id']);
// 				$member->add_points(($de['cost']+$de['freight'])*-1,'3',$de['order_id'],$de['member_id']);

                if($de['ms_id']>0){//如果是已支付的微店订单，则把已经写入的红包数据状态改为-9
                    //查找要更新的红包ID
                    $sql = "select bonus_id from ".MICROSHOPBONUSSALES." where order_id={$oid}";
                    $this->db->query($sql);
                    $sales = $this->db->getRows();
                     
                    $sql = "select bonus_id from ".MICROSHOPBONUSSERVICE." where order_id={$oid}";
                    $this->db->query($sql);
                    $service = $this->db->getRows();
                     
                    $bonus = array_merge($sales,$service);
                    $bonusIds = "";
                    foreach ($bonus as $bId)
                    {
                        $bonusIds .= (empty($bonusIds) ? "" : ",").$bId['bonus_id'];
                    }
                    
                    if(!empty($bonusIds)){
                        $sql = "update ".MICROSHOPBONUSDETAIL." set status=-9 where id in({$bonusIds}) and status=-1";
                        $this->db->query($sql);
                    }
                }
			}
			/* $post['action']='update';
			$post['seller_email']=$de['ms_id'];
			$post['buyer_email']=$de['member_id'];//卖家账号
			$post['order_id']=$de['order_id'];
			$post['statu']=0;
			$res=pay_get_url($post,true); */
			
			$sql="update ".ORDER." set status='0',finished_time=".time()." where order_id='$oid'";
			$this->db->query($sql);
			$this->order_log($de['order_id'],'订单取消','取消','',$admin);
			$sql="select a.product_id,a.num,a.microstock_num,a.seckill_id,a.supplier_id from ".ORPRO." as a where a.order_id='$oid'";
			$this->db->query($sql);
			$re=$this->db->getRows();
			//余额返还
			if($de['cash_price']>0){
			    include_once($config["webroot"]."/module/product/includes/plugin_tarento_class.php");
			    $tarento = new Tarento();
			    $tarento->change_member_account($de['member_id'], $de['cash_price'], 'CANCEL_ORDER','订单取消余额支付返还');
			}
			//微店优惠券返还
			if($de['ms_id']>0 && $de['cpns_price']>0){
			    $sql = "update ".MICROSHOPCOUPONS." set status=0,order_id='',use_time='0000-00-00 00:00:00' where order_id={$oid} and status=1";
			    $this->db->query($sql);
			}
            if ($de['status'] <= 2) {
                //库存
                foreach ($re as $val) {
                    $true_nums = $val['num'] - $val['microstock_num'];
                    if ($true_nums > 0) {
                        if($val['supplier_id']>0){//供应商仓库
                            $this->db->query("update haiou_stock_supplie_products set stock = stock+" . $true_nums . " where product_sku_id=" . $val['product_id'] . " and supplieid=" .$val['supplier_id']);
                        }else{
                            if ($de['status'] < 2) {
                                $this->db->query("update haiou_stock_stocks set sold_num=sold_num-" . $true_nums . " where productid=" . $val['product_id']." and shopid=".$de['stock_shop']);
                                $this->db->query("update " . SETMEAL . " set stock = stock+" . $true_nums . ",sell_amount=sell_amount-" . $true_nums . " where id=" . $val['product_id']." and stock_shop=".$de['stock_shop']);
                            }
                        }
//                         // 秒杀库存
//                         if ($de['status'] < 2 && ! empty($val['seckill_id'])) {
//                             $this->db->query("update " . ACTIVITYSPIKE . " set sec_stock = sec_stock+" . $true_nums . " where id=" . $val['seckill_id']);
//                         }
                    }
                    if ($de['status'] < 2 && $val['microstock_num']){
                        $this->db->query("update ".MICROSTOCK." set num=num+{$val['microstock_num']} where member_id={$de['member_id']} and sku_id={$val['product_id']} and stock_shop={$de['stock_shop']} limit 1 ");
                    }
                }
            }
		}
		if($status==2)	//===========付款
		{
			/* include_once("module/member/includes/plugin_member_class.php");
			$member = new member();		
			$member->add_growth(($de['cost']+$de['freight'])*1,$de['member_id']);
			$member->add_points(($de['cost']+$de['freight'])*1,'1',$de['order_id'],$de['member_id']); */
			
			/* $post['action']='update';
			$post['seller_email']=$de['ms_id'];
			$post['buyer_email']=$de['member_id'];//买家账号
			$post['order_id']=$de['order_id'];
			$post['statu']=2; */
			//$res=pay_get_url($post,true);//跳转至订单生成页面
			//$sql="update ".ORDERPAYMENT." set end_time='".time()."',status='2' where order_id='$de[order_id]'";
			//$this->db->query($sql);
			$sql="update ".ORDER." set status='2',pay_status='2',pay_time=".time()." where order_id='$oid'";
			$this->db->query($sql);
			$this->order_log($de['order_id'],'订单付款完成','付款','',$admin);
			
// 			微店需要拆单的订单，进行拆单
			if($de['ms_id']>0){
			    if($de['separate_status']==1){//需要拆
    			    $sRes = $this->separateOrder($de['order_id']);
    			    if($sRes){//如果拆单成功，1处理自营库存，2加销售额和发红包
    			        $sql = "select GROUP_CONCAT(order_id) as sOid from ".ORDER." where master_order_id={$oid}";
    			        $this->db->query($sql);
    			        $sOid = $this->db->fetchField('sOid');
    			        
    			        //自营商品减库存
    			        $sql="select a.product_id,a.num,b.stock_relations,a.order_id,c.stock_shop from ".ORPRO." as a left join ".ORDER." as c on a.order_id=c.order_id left join ".SETMEAL." as b on a.product_id=b.id where a.order_id in({$sOid}) and a.supplier_id=0";
            			$this->db->query($sql);
            			$sPro=$this->db->getRows();
            			
            			if(!empty($sPro)){
            			    include_once($config['webroot']."/module/product/inventory_api.php");
            			    foreach($sPro as $val)
            			    {
            			        if(!empty($val['num']))
            			        {
            			            //减库存zxzxzx减库存
            			            reduceInventory($val['product_id'].'_'.$val['stock_relations'],$val['num'],$val['order_id'],$val['stock_shop']);
            			        }
            			    }
            			}
            			
//             			//加销售额和发红包
            			$sOrderIds = explode(',', $sOid);
            			foreach ($sOrderIds as $subOid)
            			{
            			    $this->order_log($subOid,'拆单循环订单号','加销售额和发红包','',$admin);
            			    $this->updateSaleInfoAndGiveBonus($subOid);
            			}
    			    }
    			    
    			    return true;
			    }else{//不需要拆
			        $sql = "select supplier_id from ".ORPRO." where order_id={$oid} limit 1";
			        $this->db->query($sql);
			        $supplierId = $this->db->fetchField('supplier_id');
			        if($supplierId>0){//如果是供应商的订单
			            $sql = "update ".ORDER." set separate_status=-{$supplierId} where order_id={$oid}";
			            $this->db->query($sql);
			        }
			    }
			}
			
			include_once($config['webroot']."/module/product/inventory_api.php");
			$sql="select a.product_id,a.num as nums,a.microstock_num,b.stock_relations from ".ORPRO." as a left join ".SETMEAL." as b on a.product_id=b.id where a.order_id='$oid' and a.supplier_id=0";
			$this->db->query($sql);
			$re=$this->db->getRows();
			foreach($re as $val)
			{
				if(!empty($val['nums']))
				{
					//减库存zxzxzx减库存
					reduceInventory($val['product_id'].'_'.$val['stock_relations'],$val['nums'],$oid,$de['stock_shop']);
				}
				if (!empty($val['microstock_num'])){
			            //微仓出库处理
			         $this->db->query("select pid from ".SETMEAL. " where id={$val['product_id']} limit 1");
			         $pid=$this->db->fetchField('pid');
			         $this->db->query("insert into ".MICROSTOCKOUT." set member_id={$de['member_id']},order_id='{$de['order_id']}',sku_id={$val['product_id']},pid={$pid},stock_shop={$de['stock_shop']},num={$val['microstock_num']}");
			            
			     }
			}
		    
		    if($de['ms_id']>0){//微店订单，加销售额
		        $this->updateSaleInfoAndGiveBonus($oid);
		    }
		    else{
		        //放入返利处理队列
		        include_once("$config[webroot]/lib/Httpsqs.php");
		        Httpsqs::put('tarentoOrder',array('order_id'=>$oid));
		    }
		}
		if($status==3) //===========发货
		{
			/* $post['action']='update';
			$post['seller_email']=$de['ms_id'];
			$post['buyer_email']=$de['member_id'];//买家账号
			$post['order_id']=$de['order_id'];
			$post['statu']=3;
			$res=pay_get_url($post,true);//跳转至订单生成页面 */
			$sql="update ".ORDER." set status='3',ship_status=2,ship_time=".time()." where order_id='$oid'";
			$this->db->query($sql);
			//订阅物流
			$this->subscriberShipping($oid);
			//发送发货短信
			$this->sendShippedMsg($oid);
			
			$this->order_log($de['order_id'],'订单已发货','发货','',$admin);
			
			//给店主推送消息
			$replaceArr = [];
			$param = [
			    'memberId'=>$de['member_id'],
			    'keyword1'=>'订单号:'.$oid,
			    'keyword2'=>$de['shipping_name'],
			    'keyword3'=>$de['shipping_no'],
			    'keyword4'=>$de['ship_addr'],
			    'url'     =>'http://wx.52ywy.com/?shop='.$de['ms_id'].'#&cart/orderdetail/?id='.$oid
			];
			include_once($config["webroot"]."/lib/Helper.php");
			Helper::pushMessage('orderShipped', $replaceArr, $param);
		}
		if($status==4 && $de['status']==3)
		{	
			/* $post['action']='update';
			$post['seller_email']=$de['ms_id'];
			$post['buyer_email']=$de['member_id'];//买家账号
			$post['order_id']=$de['order_id'];
			$post['statu']=4;
			$res=pay_get_url($post,true);//跳转至订单生成页面 */
			$sql="update ".ORDER." set status='4',finished_time=".time()." where order_id='$oid'";
			$this->db->query($sql);
			include_once($config['webroot']."/module/member/includes/plugin_member_class.php");
			$member = new member();
			$member->add_growth($de['member_id'],($de['cost']+$de['freight']-$de['discount']-$de['cpns_price'])*1,$de['order_id']);
// 			$member->add_points($de['member_id'],($de['cost']+$de['freight']-$de['discount']-$de['cpns_price'])*1,'ORDER_FINISH',$de['order_id']); 
			$this->order_log($de['order_id'],'订单完成','完成','',$admin);
			if($de['ms_id']>0){//微店订单，发红包
			    include_once($config['webroot']."/module/micro_shop/includes/plugin_micro_shop_class.php");
			    $microShop = new MicroShop();
			    $microShop->updateBonusAfterFinishOrder($oid);
			}
		}
		if($status==5)
		{
			/* $post['action']='update';
			$post['seller_email']=$de['ms_id'];
			$post['buyer_email']=$de['member_id'];//买家账号
			$post['order_id']=$de['order_id'];
			$post['statu']=5;
			$res=pay_get_url($post,true);//跳转至订单生成页面 */
		}
		if($status==6)//退款，由买家发起，管理员进行退款操作。
		{	
			/* $post['action']='update';
			$post['seller_email']=$de['ms_id'];
			$post['buyer_email']=$de['member_id'];//买家账号
			$post['order_id']=$de['order_id'];
			$post['statu']=6;
			$res=pay_get_url($post,true);//跳转至订单生成页面 */
		}
		
		
	
		/* if(!empty($res))
		{
			$res=json_decode($res);
			if($res->statu=='true'&&$res->auth!=md5($config['authkey']))
			{
				//------------如果结果正常就对订单进行取消操作。
				$sql="update ".ORDER." set status='$status',finished_time=".time()." where order_id='$oid'";
				$this->db->query($sql);
			}
			return true;
		}
		else
			return false; */
	}
	function order_log($order_id,$text,$behavior,$admin_id=NULL,$admin_name=NULL)
	{
		if(!$order_id) return false;
		$admin_name=$admin_name?$admin_name:NULL;
		if($admin_name)
		{
			$sql="SELECT id FROM ".ADMIN." WHERE user='$admin_name'";
			$this->db->query($sql);
			$admin_id=$this->db->fetchField('id');
		}
		$admin_id=$admin_id?$admin_id:0;
		$sql="insert into ".ORDERLOG."(order_id,admin_id,admin_name,text,behavior,result) VALUES ('$order_id','$admin_id','$admin_name','$text','$behavior','success')";
		$this->db->query($sql);	
			
	}
	function shop_order_log($order_id)
	{
		if(!$order_id) return false;
		$sql="select * from ".ORDERLOG." where order_id=".$order_id."";
		$this->db->query($sql);
		$re=$this->db->getRows();
		return $re;
	}
	function add_order_delivery($order_id,$ship,$consignee)
	{
		global $buid;
		if(!$order_id) return false;
		$sql="insert into ".ORDERDELIVERY."(`order_id`,`member_id`,`money`,`shipping_id`,`shipping_name`,`shipping_no`,`ship_name`,`ship_addr`,`ship_zip`,`ship_tel`,`ship_mobile`,`start_time`,`end_time`,`status`) VALUES ('$order_id','$buid','$ship[price]','$ship[id]','$ship[title]','','$consignee[name]','$consignee[area]','$consignee[zip]','$consignee[tel]','$consignee[mobile]','".time()."','0','1')";
		$this->db->query($sql);	
	}
	function add_order_payment($order_id,$price,$pay)
	{
		global $buid;
		if(!$order_id) return false;
		$payment_type=$pay['payment_type']!="cod"?"online":"offline";
		$ip=getip();$ip=empty($ip)?NULL:$ip;
		$sql="insert into ".ORDERPAYMENT."(`order_id`,`member_id`,`money`,`payment_type`,`payment_id`,`payment_name`,`ip`,`start_time`,`end_time`,`status`,`trade_no`) VALUES ('$order_id','$buid','$price','$payment_type','$pay[payment_id]','$pay[payment_name]','$ip','".time()."','0','1','')";
		$this->db->query($sql);	
	}
	
	function get_express(){
		$sql="select * from ".FASTMAIL."  order by id DESC";
		$this->db->query($sql);
		$re=$this->db->getRows();
		return $re;
	}
	function get_inventory_status($oid){
		include_once WEBROOT.'/module/inventory/config.inc.php';
		$inventory_config = new config();
		$sql="SELECT id  FROM ".$inventory_config->db_prefix."orders where lotnumber = '$oid' and type=0 and timestocked=0";
		//====================
		$this->db->query($sql);
		if($returns=$this->db->getRows()){
			return $returns;
		}else{
			return 0;
		}

	}
	function get_order_remark_list($oid){
		$sql = "select * from haiou_order_remark where order_id='{$oid}'";
		$this->db->query($sql);
		$re = $this->db->getRows();
		return $re;
	}
	function get_stock_shops(){//发货库房
		$sql ="select * from " .STOCKSHOP. " where 1";
	
		$this->db->query($sql);
		$stock_shops=$this->db->getRows();
		return $stock_shops;
	}
	
	function get_general_shop(){//绑定库房
	$sql =" select shopid from ". STOCKGENERAL . " as t1  where t1.admin_name= '{$_SESSION['ADMIN_USER']}'";
			$this->db->query($sql);
			if(!$stockshop=$this->db->fetchField('shopid')){
				$stockshop =0;
			}
		return $stockshop;
	}
	
	function get_order_express_pro($order_id,&$sum=0,&$total_num=0)
	{
		global $config,$buid;
		include($config['webroot'].'/lang/cn/company_type_config.php');
		
		$sum = 0;
		$total_num = 0;
		
		$sql="select a.*,b.pname as name,b.pid as pid, b.spec,b.code,b.brand,b.declared_price,c.waiting_time,c.waiting_time_end,d.cat,c.hscode,e.unit,e.min_realpricebuy from ".ORPRO." a left join ".SETMEAL." b on a.product_id=b.id left join ".PRO." as c on b.pid=c.id left join ".PCATCUSTOMS." as d on c.hscode=d.hscode left join haiou_stock_products as e on a.product_id=e.product_sku_id where a.order_id='$order_id' and a.is_stocked>=0";
		$this->db->query($sql);
		$re=$this->db->getRows();
		foreach($re as $key=>$val)
		{
			if($val['waiting_time']!="" && $val['waiting_time_end']!=""){
				$re[$key]['waiting_time_desc'] = $val['waiting_time']."-".$val['waiting_time_end']."天发货";
			}elseif($val['waiting_time']!=""){
				$re[$key]['waiting_time_desc'] = $val['waiting_time']."天发货";
			}elseif($val['waiting_time_end']!=""){
				$re[$key]['waiting_time_desc'] = $val['waiting_time_end']."天发货";
			}else{
				$re[$key]['waiting_time_desc'] = "暂无";
			}
			$re[$key]['name'] .="　".$val['spec'];
			$sku_total_price = $val['declared_price']*$val['num'];
			$re[$key]['sum']=$sku_total_price;
			$sum += $sku_total_price;//总申报价值
			$total_num += $val['num'];//商品SKU总数量
		}
		return $re;
	}
	
	/**
	 * 获取订单商品库存产品信息
	 * @param unknown $order_id
	 */
	public function get_order_product_stock_info($order_id){
	    $sql = "select a.product_id,a.product_name,a.num,b.pid,b.brand,d.barcode,c.sbarcode,c.pricebuy from ".ORPRO." a left join ".SETMEAL." b on a.product_id=b.id left join haiou_stock_supplie_products c on a.product_id=c.product_sku_id AND c.supplieid=a.supplier_id left join haiou_stock_products d on a.product_id=d.product_sku_id where a.order_id='{$order_id}' GROUP BY a.id";
	    $this->db->query($sql);
	    $res = $this->db->getRows();
	    
	    return $res;
	}
	
	/**
	 * 给用户发送已发货的短信
	 * @param unknown $order_id
	 */
	function sendShippedMsg($order_id){
		global $db,$config;
		include_once("$config[webroot]/lib/Httpsqs.php");
		
    	if (!ctype_digit((string)$order_id)) {
            return false;
        }
        
        if(!$this->isOpenShipmentsSms){ //没有开启
            return false;
        }
        $orderId = $order_id;
        //获取号码和仓库
        $sql="select member_id,stock_shop,order_type from ".ORDER." where order_id='{$orderId}'";
        $db->query($sql);
        $orderInfo=$db->fetchRow();
        $sql="SELECT `mobile` FROM `haiou_member` WHERE `userid`={$orderInfo['member_id']} AND `mobile`!='' LIMIT 1";
        $db->query($sql);
        $memberInfo=$db->fetchRow();
        if(!empty($memberInfo['mobile'])){ //此用户绑定了手机号
            $mobile = $memberInfo['mobile'];
            //获取仓库名
            $sql="select title from haiou_stock_shops where id='{$orderInfo['stock_shop']}'";
            $db->query($sql);
            $res=$db->fetchRow();
            $stockShopName = $res['title'];
            //获取短信内容
            $sql="SELECT `message` FROM `haiou_mail_mod` WHERE `flag`='shipments' AND `type`=2 LIMIT 1";
            $db->query($sql);
            $smsData=$db->fetchRow();
            if(!empty($smsData)){
                $message = $smsData['message'];
                $message = str_replace('{{发货地}}', $stockShopName, $message);
                $message = str_replace('{{订单号}}', $orderId, $message);
                $queueData['Mobile']  = $mobile;
                $queueData['Content'] = $message;
                if ($orderInfo['order_type'] == 3) {
                    //微店平台
                    $queueData['platform'] = 'microShop';
                }
                Httpsqs::put('sendSMS',$queueData);
            }
        }
	}
	
	/**
	 * 订阅物流
	 * @param number $orderId
	 * @return boolean
	 */
	function subscriberShipping ($orderId) {
		global $db;
		$status = false;
		$sql="select `ho`.`shipping_no`,`ho`.`shipping_express_id`,`ho`.`stock_shop`,`hle`.`subscriber_code` from ".ORDER." AS `ho` LEFT JOIN `haiou_logistics_express` AS `hle` ON `ho`.`shipping_express_id`=`hle`.`id` where order_id='{$orderId}'";
		$db->query($sql);
		$orderInfo=$db->fetchRow();
		if(!empty($orderInfo['shipping_no']) && !empty($orderInfo['subscriber_code']))
		{
    		$orderInfo['subscriber_code'] = strtolower($orderInfo['subscriber_code']);
			//获取发货地
			$sql = "SELECT `country_en`,`title` FROM `haiou_stock_shops` WHERE `id`={$orderInfo['stock_shop']}";
			$db->query($sql);
			$stockInfo = $db->fetchRow();
			$fromCity = strtolower($stockInfo['country_en']);
			//获取收货地
			$sql="SELECT `hd_p`.`name` AS `p_name`,`hd`.`name` AS `c_name`,`ho`.`member_id` FROM haiou_order AS `ho` LEFT JOIN `haiou_district` AS `hd` ON `hd`.`zip`=`ho`.`ship_zip`  LEFT JOIN `haiou_district` AS `hd_p` ON  `hd_p`.id=`hd`.`pid` WHERE `ho`.`order_id`='{$orderId}' LIMIT 1";
			$db->query($sql);
			$de=$db->fetchRow();
			$toCity = $de['p_name'].$de['c_name'];
			$durl = 'http://app.milanoo.com/delivery/subscriber/doSecSubscripton.htm';
			$data = array(
					"company"=>$orderInfo['subscriber_code'],
					"pj"=>"haioo",
					"number"=>$orderInfo['shipping_no'],
					"from"=>$fromCity,
					"to"=>$toCity,
			);
			ksort($data);
			$data = array_reverse($data);
			#计算sign
			$paramStr = "";
			foreach($data as $k=>$v){
				if($paramStr != ""){
					$paramStr .= '&';
				}
				$paramStr .= "{$k}={$v}";
			}
			$data['sign'] = strtoupper(md5($paramStr."|RjU3REQ3M0EzRUZGRjQ5OUU2NTA4MEZEQkQ2MkQyMUY="));
			$res = curl_file_get_contents($durl,$data);
			$res = @gzuncompress($res);
			$res  = json_decode($res,true);
			//失败写入日志
			if(!isset($res['code']) || $res['code']!='0'){
				$status = '-1';
			} else {
				$status = '1';
			}
			$nowDate = date('Y-m-d H:i:s');
			$desc = json_encode($res);
			$desc .= ' ; '.json_encode($data);
			$sqlstr = "insert into haiou_kuaidi_subscriber (order_id, shipping_no, status,`desc`,create_time) values ('{$orderId}','{$orderInfo['shipping_no']}',$status,'$desc','{$nowDate}')";
			$db->query($sqlstr);
		}
		return $status;
	}
	
	/**
	 * 获取销售额
	 * @param number $shopId 仓库ID
	 * @param number $timeType 1为今天数据，2为昨天数据，3为本月数据
	 * @param number $orderType 0为全部，1普通订单 ，2分销订单 ，3微店订单
	 * @param string $cond 自定条件
	 */
	public function getSalesInfo($shopId=0,$timeType=3,$orderType=0,$cond="")
	{
	    global $db;
	    if(!empty($cond)){
	        $str = $cond;
	    }else{
    	    $str = " and status>1";
    	    if($shopId>0){
    	        $str .= " and stock_shop={$shopId} ";
    	    }
    	    switch ($timeType)
    	    {
    	        case 1://今天
    	            $time = strtotime(date('Y-m-d'));
    	            $str .= " and order_time>='{$time}'";
    	            break;
    	        case 2://昨天
    	            $time = strtotime(date('Y-m-d',strtotime('-1 day')));
    	            $rtime = $time+86399;
    	            $str .= " and order_time>='{$time}' and order_time<='{$rtime}'";
    	            break;
    	        case 3://本月
    	            $time = strtotime(date('Y-m'));
    	            $str .= " and order_time>='{$time}'";
    	            break;
                default://全部
                    break;
    	    }
	    }
	    
	    if($orderType>0){
	        $str .= " and order_type={$orderType}";
	    }
	    
	    $sql = "select sum(cost+freight+tax_price+insurance_fee-cpns_price-discount) as total from ".ORDER." where 1 {$str}";
	    $db->query($sql);
	    $total = $db->fetchField('total');
	    
	    return $total?$total:0;
	}
	
	/**
	 * 获取订单数量
	 * @param number $shopId 仓库ID
	 * @param number $timeType 1为今天数据，2为昨天数据，3为本月数据
	 * @param number $orderType 0为全部，1普通订单 ，2分销订单 ，3微店订单
	 */
	public function getOrderNum($shopId=0,$timeType=3,$orderType=0) {
	    global $db;
	    $str = "status>1";
	    if($shopId>0){
	        $str .= " and stock_shop={$shopId} ";
	    }
	    switch ($timeType)
	    {
	        case 1://今天
	            $time = strtotime(date('Y-m-d'));
	            $str .= " and order_time>='{$time}'";
	            break;
	        case 2://昨天
	            $time = strtotime(date('Y-m-d',strtotime('-1 day')));
	            $rtime = $time+86399;
	            $str .= " and order_time>='{$time}' and order_time<='{$rtime}'";
	            break;
	        case 3://本月
	            $time = strtotime(date('Y-m'));
	            $str .= " and order_time>='{$time}'";
	            break;
	        default://全部
	            break;
	    }
	    
	    if($orderType>0){
	        $str .= " and order_type={$orderType}";
	    }
	    
	    $sql="select count(*) as total from ".ORDER." where {$str}";
	    $db->query($sql);
	    $total = $db->fetchField('total');
	     
	    return $total?$total:0;
	}
	
	/**
	 * 获取订单优惠券使用金额
	 * @param number $timeType 1为今天数据，2为昨天数据，3为本月数据
	 * @param number $orderType 0为全部，1普通订单 ，2分销订单 ，3微店订单
	 */
	public function getCpnsPrice($timeType=3,$orderType=0){
	    global $db;
	    $str = " and status>1";

	    switch ($timeType)
	    {
	        case 1://今天
	            $time = strtotime(date('Y-m-d'));
	            $str .= " and order_time>='{$time}'";
	            break;
	        case 2://昨天
	            $time = strtotime(date('Y-m-d',strtotime('-1 day')));
	            $rtime = $time+86399;
	            $str .= " and order_time>='{$time}' and order_time<='{$rtime}'";
	            break;
	        case 3://本月
	            $time = strtotime(date('Y-m'));
	            $str .= " and order_time>='{$time}'";
	            break;
	        default://全部
	            break;
	    }
	    
	    if($orderType>0){
	        $str .= " and order_type={$orderType}";
	    }
	     
	    $sql = "select sum(cpns_price) as total from ".ORDER." where 1 {$str}";
	    $db->query($sql);
	    $total = $db->fetchField('total');
	     
	    return $total?$total:0;
	}
	
	/**
	 * 获取快递运单号
	 * @param unknown $expressId 快递ID
	 */
	public function getExpressNo($expressId) {
	    $expressNo = '';
	    $sql = "select * from ".FASTMAIL." where id={$expressId}";
	    $this->db->query($sql);
	    $expressInfo = $this->db->fetchRow();
	    
	    switch ($expressId)
	    {
	        case 19://sps邮政小包
	            if(!empty($expressInfo)){
    	            //计算校验位数值
	                $c = 0;
	                //加权因子(左到右):8642 3597
	                $temp = $expressInfo['express_no_current'];
	                $code1 = 8*$temp{0}+6*$temp{1}+4*$temp{2}+2*$temp{3}+3*$temp{4}+5*$temp{5}+9*$temp{6}+7*$temp{7};
	                $code2 = $code1%11;
	                $code3 = $code2==0?6:$code2;
	                $code4 = $code3==1?11:$code3;
	                $c     = 11-$code4;
	                
    	            //拼出运单号
    	            if(intval($expressInfo['express_no_current']) <= intval($expressInfo['express_no_last'])){
    	               $expressNo = $expressInfo['express_no_pre'].$expressInfo['express_no_current'].$c.$expressInfo['express_no_pos'];
    	               //计算出下一次运单号中间的基串并存入
    	               $new = intval($expressInfo['express_no_current'])+1;
    	               $new_len = strlen($new);
    	               if($new_len!=8){
    	                   $new = str_pad ( $new ,  8 ,  "0" ,  STR_PAD_LEFT );
    	               }
    	               $sql = "update ".FASTMAIL." set express_no_current='{$new}' where id={$expressId}";
    	               $this->db->query($sql);
    	            }
	            }
	            break;
            default:
                break;
	    }
	    
	    return $expressNo;
	}
	
	/**
	 * 获取快递可自动分配运单号数量
	 * @param unknown $expressId
	 */
	public function getExpressNoRestNum($expressId) {
	    $num = 0;
	    $sql = "select * from ".FASTMAIL." where id={$expressId}";
	    $this->db->query($sql);
	    $expressInfo = $this->db->fetchRow();
	     
        if(!empty($expressInfo)){
    	    switch ($expressId)
    	    {
    	        case 19://sps邮政小包
    	            $num = intval($expressInfo['express_no_last'])-intval($expressInfo['express_no_current'])+1;
    	            break;
    	        default:
    	            break;
    	    }
        }
	     
	    return $num;
	}
	
	/**
	 * 更新微店销售额和发红包
	 * @param unknown $oid
	 */
	public function updateSaleInfoAndGiveBonus($oid){
	    global $config;
	    
	    $sql="select order_id,ms_id,member_id,status,cost,discount,cpns_price,cash_price,freight,stock_shop,shipping_name,shipping_no,ship_addr,ship_name,separate_status from ".ORDER." where order_id='$oid'";
	    $this->db->query($sql);
	    $de=$this->db->fetchRow();
	    
	    //给用户推送消息
	    $replaceArr = [];
	    //订单商品信息
	    $sql = "select product_name from ".ORPRO." where order_id='{$oid}' limit 1";
	    $this->db->query($sql);
	    $productName = $this->db->fetchField('product_name');
	    $param = [
	        'memberId'=>$de['member_id'],
	        'orderProductPrice'=>$config['money'].' '.$de['cost'],
	        'orderProductName'=>$productName,
	        'orderAddress'=>$de['ship_name'].','.$de['ship_addr'],
	        'orderName'=>$oid,
	        'url'=>'http://wx.52ywy.com/?shop='.$de['ms_id'].'#&cart/orderdetail/?id='.$oid
	    ];
	    include_once($config["webroot"]."/lib/Helper.php");
	    Helper::pushMessage('orderPaySuccess', $replaceArr, $param);
	    
	    include_once($config['webroot']."/module/micro_shop/includes/plugin_micro_shop_class.php");
	    $microShop = new MicroShop();
	    $microShop->updateSalesInfoByOrder($oid);//更新销售额
	    
	    //发红包
	    $microShop->giveOutBonusOfOrder($oid);
	}
	
	/**
	 * 生成订单号
	 * @param string $memberId
	 * @param number $orderType
	 */
	public function createOrderId($memberId,$orderType=3){
	    $order_id = "";
	    
	    $d=getdate();
	    $prefix= date('y');
	    
	    switch ($orderType)
	    {
	        case 1:
	            break;
	        case 2:
	            break;
	        case 3://微店的订单号规则
	            $prefix.=str_pad($d['yday'],3,0,STR_PAD_LEFT);
	            $prefix.= str_pad(time()- strtotime(date('Y-m-d')),5,0,STR_PAD_LEFT);
	            $order_id=$prefix.str_pad(substr($memberId,-5,5),5,0,STR_PAD_LEFT).rand(0,9);
	            break;
            default:
                break;
	    }
	    
	    return $order_id;
	}
	
	/**
	 * 拆分订单
	 * @param unknown $orderId
	 */
	public function separateOrder($orderId){
	    $sql = "select * from ".ORPRO." where order_id={$orderId}";
	    $this->db->query($sql);
	    $orderProduct = $this->db->getRows();
	    
	    $newPro = [];
	    foreach ($orderProduct as $key=>$val)
	    {
	        $newPro[$val['stock_shop']][] = $val;
	    }
	    $nums = count($newPro);
	    $cpns_priceamount = '';
	    $cash_priceamount = '';
	    $freightamount = '';
	    $total_ms_taxationamount = '';
	    $shippingId = '';
	    $shippingName = '';
	        
	    
	    if(count($newPro)>1){
	        $i = 0;
	        foreach ($newPro as $k=>$v)
	        {
	            $newOrderId = $this->createOrderId($orderProduct[0]['member_id']);
	            $newOrderId .= ($i+1);
	            $ms_discount = 0;
	            $cost = 0;
	            //订单商品信息
	            $orderPro = "";
	            foreach ($v as $pro)
	            {
	                $ms_discount += $pro['ms_discount'];
	                $cost += $pro['price'] * $pro['num'];
	                $pro['product_name'] = @mysql_escape_string($pro['product_name']);
	                $orderPro .= (empty($orderPro) ? "(" : ",(")."'{$newOrderId}','{$pro['member_id']}','{$pro['product_id']}','{$pro['pcatid']}','{$pro['product_name']}','{$pro['property']}','{$pro['pic']}','{$pro['price']}','{$pro['ms_discount']}','{$pro['supplier_id']}','{$pro['num']}','{$pro['logisticsId']}','{$pro['stock_shop']}','{$pro['tax_price']}','{$pro['active_id']}')";
	                //查询配送方式
	                $shippingId = $pro['logisticsId'];
	                $sql = "select * from haiou_logistics_temp where id = ".$shippingId;
	                $this->db->query($sql);
	                $shippingInfo = $this->db->fetchRow();
	            }
	            $sql = "insert into ".ORPRO." (`order_id`,`member_id`,`product_id`,`pcatid`,`product_name`,`property`,`pic`,`price`,`ms_discount`,`supplier_id`,`num`,`logisticsId`,`stock_shop`,`tax_price`,`active_id`) values".$orderPro;
	            $this->db->query($sql);
	            
	            //订单信息
	            $sql = "select * from ".ORDER." where order_id={$orderId}";
	            $this->db->query($sql);
	            $oldOrderInfo = $this->db->fetchRow();

// 	            if($oldOrderInfo['warehouse_type'] == 1){
// 	                $shopId = 20;
// 	            }elseif($oldOrderInfo['warehouse_type'] == 2){
// 	                $shopId = 15;
// 	            }else{
// 	                $shopId = $oldOrderInfo['stock_shop'];
// 	            }
// 	            if($k>0){
//     	            //供应商所在仓库
//     	            $sql = "select shopid from haiou_stock_suppliers where id={$k}";
//     	            $this->db->query($sql);
//     	            $shopId = $this->db->fetchField('shopid');
// 	            }
	            $rate = $cost/$oldOrderInfo['cost'];
	            
	            if($nums-$i == 1){
	                $cpns_price = $oldOrderInfo['cpns_price'] - $cpns_priceamount;
	                $freight = $oldOrderInfo['freight'] - $freightamount;
	                $total_ms_taxation = ($oldOrderInfo['total_ms_taxation'] * $rate) - $total_ms_taxationamount;
	            }else{
	                $cpns_price = ceil($oldOrderInfo['cpns_price'] * $rate);
	                $freight = ceil($oldOrderInfo['freight'] * $rate);
	                $total_ms_taxation = ceil($oldOrderInfo['total_ms_taxation'] * $rate);
	                
	                $cpns_priceamount +=  ceil($oldOrderInfo['cpns_price'] * $rate);
	                $cash_priceamount +=  ceil($oldOrderInfo['cash_price'] * $rate);
	                $freightamount +=  ceil($oldOrderInfo['freight'] * $rate);
	                $total_ms_taxationamount += ceil($oldOrderInfo['total_ms_taxation'] * $rate);
	            }
	            $ms_Freight_risk = $oldOrderInfo['ms_Freight_risk']/$nums;
	            
	            $cash_price = $cost + $total_ms_taxation + $ms_Freight_risk + $freight - $cpns_price;
	            
	            $orderCreateData = [
	                'member_id'	        => $oldOrderInfo['member_id'],
	                'order_id'			=> $newOrderId,
	                'master_order_id'	=> $orderId,
	                'ms_id'             => $oldOrderInfo['ms_id'],
	                'order_time'		=> $oldOrderInfo['order_time'],
	                'order_type'        => $oldOrderInfo['order_type'],
	                'status'		    => 2,
	                'pay_status'		=> 2,
	                'separate_status'	=> $k>0 ? -$k : 0,
	                'pay_time'		    => $oldOrderInfo['pay_time'],
	                'payment_id'		=> $oldOrderInfo['payment_id'],
	                'warehouse_type'	=> $oldOrderInfo['warehouse_type'],
	                'payment_name'      => $oldOrderInfo['payment_name'],
	                'shipping_id'       => $shippingId,
	                'shipping_name'     => $shippingInfo['title'],
	                'ship_name'         => $oldOrderInfo['ship_name'],
	                'ship_addr'         => $oldOrderInfo['ship_addr'],
	                'ship_mobile'       => $oldOrderInfo['ship_mobile'],
	                'shipping_idcard'   => $oldOrderInfo['shipping_idcard'],
	                'ship_zip'          => $oldOrderInfo['ship_zip'],
	                'cpns_price'        => $cpns_price,
	                'cash_price'        => $cash_price,
	                'cost'              => $cost,
	                'ms_discount'       => $ms_discount,
	                'freight'           => $freight,
	                'weight'            => $oldOrderInfo['weight'],
	                'stock_shop'        => $k,
	                'client_system'     => $oldOrderInfo['client_system'],
	                'client_platform'   => $oldOrderInfo['client_platform'],
	                'total_ms_taxation'   => $total_ms_taxation,
	                'ms_Freight_risk'   => $oldOrderInfo['ms_Freight_risk']/$nums
	            ];
	            
	            $newOrderKey = "(";
	            $newOrderValue = "(";
	            foreach ($orderCreateData as $kk=>$vv)
	            {
	                $newOrderKey .= "`{$kk}`,";
	                $newOrderValue .= "'{$vv}',";
	            }
	            $newOrderKey = rtrim($newOrderKey,',');
	            $newOrderValue = rtrim($newOrderValue,',');
	            $newOrderKey .= ")";
	            $newOrderValue .= ")";
	            
	            $sql = "insert into ".ORDER." {$newOrderKey} values{$newOrderValue}";
	            $this->db->query($sql);
	            
	            $i++;
	        }
	        
	        //拆完后把原订单状态改变
	        $sql = "update ".ORDER." set status=-9,separate_status=2 where order_id={$orderId}";
	        $this->db->query($sql);
	        
	        return true;
	    }
	    
	    return false;
	}
}
?>
